//
//  SourceListElementDownloads.m
//  SolarSeek
//
//  Created by Erick Fejta on 05/04/23.
//  Copyright 2005 Erick Fejta. All rights reserved.
//

#import "SourceListElementDownloads.h"
#import "SolarSeekEngine.h"
#import "SolarSeekApplication.h"
#import "TransfersController.h"
#import "TransferView.h"
#import "Transfers.h"
#import "ApplicationDefaults.h"

@interface SourceListElementDownloads (Private)
- (double)speed;
@end

@implementation SourceListElementDownloads
- (id)initWithView:(NSView *)view {
	if(self = [super initWithView:view]) {
		SolarSeekEngine *engine = [NSApp engine];
		[[engine transfersController] addObserver:self forKeyPath:@"transferCreated" options:nil context:nil];
	}
	return self;
}

- (void)dealloc {
	TransfersController *tc = [[NSApp engine] transfersController];
	[tc removeObserver:self forKeyPath:@"transferCreated"];
	[super dealloc];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
	if([(Transfer *)[object transferCreated] type]==[(TransferView *)[self view] type])
		[self refreshAndRequestAttention:YES];
}

#pragma mark KVO

- (NSImage *)icon { return [(TransferView *)[self view] type]==TransferTypeUpload?[NSImage imageNamed:@"sourcelistUpload"]:[NSImage imageNamed:@"sourcelistDownload"]; }
- (NSString *)name { 
	NSString *first = [self titleWindow]; 
	double speed = 0;
	NSString *second = @"";
	if([[NSUserDefaults standardUserDefaults] boolForKey:SolarSeekDefaultShowCumulativeBandwidthInformation]) {
		speed = [self speed];
		second = [[NSValueTransformer valueTransformerForName:@"SolarSeekValueTransformerSpeed"] transformedValue:[NSNumber numberWithDouble:speed]];
		NSEnumerator *e = [[[[NSApp engine] transfersController] transfersWithType:[(TransferView *)[self view] type]] objectEnumerator];
		unsigned count = 0;
		Transfer *t;
		while(t = [e nextObject]) {
			if([t state]==TransferStateTransferring)
				count++;
		}
		second = [NSString stringWithFormat:@"%d - %@",count,second];
	}
	return speed>0.05?[NSString stringWithFormat:@"%@ (%@)",first,second]:first;
}

- (NSString *)titleWindow {
	NSString *first = [(TransferView *)[self view] type]==TransferTypeUpload?@"Uploads":@"Downloads"; 
	return first;
}

- (double)speed {
	NSEnumerator *e = [[[[NSApp engine] transfersController] transfersWithType:[(TransferView *)[self view] type]] objectEnumerator];
	Transfer *t;
	double speed = 0;
	while(t = [e nextObject]) {
		if([t state]==TransferStateTransferring)
			speed += [t speed];
	}
		
	return speed;
}

@end
